package com.atguigu.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyNumber //资源类
{
    int number = 0;

    public int getNumber()
    {
        return number;
    }

    public synchronized void setNumber()
    {
        number++;
//        number--;
    }

    //---CAS
    AtomicInteger atomicInteger = new AtomicInteger();

    public int getAtomicInteger()
    {
        return atomicInteger.get();
    }

    public void setAtomicInteger()
    {
        atomicInteger.getAndIncrement();
    }
}


public class CASDemo {

    public static void main(String[] args) {
        MyNumber myNumber = new MyNumber();

        for (int i = 1; i <=200; i++) {
            new Thread(() -> {
                for (int j = 1; j <=200; j++) {
                    myNumber.setNumber();
                    myNumber.setAtomicInteger();
                }
            },String.valueOf(i)).start();
        }

        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println(myNumber.getNumber());
        System.out.println(myNumber.getAtomicInteger());
    }
}

